<?php
namespace Addons\Wukong\Model;
use Think\Model;

/**
 * 分类模型
 */
class WukongAuthModel extends WukongModel{

    /*
 * md5 hexadecimal number string to int (only first 16-character)
 */
    private function md5ToInt($hash)
    {
        $n = 0;
        for ($i = 0; $i<4; $i++)
        {
            $str = substr($hash, $i*2, 2);
            $x = intval($str, 16);
            $n  = $n << 8;
            $n |= $x;
        }
        return abs($n);
    }

    /*
     * use username + password to generate an openId, same username/password will generate same openId
     */
    public function getOpenId($username, $password)
    {
        $str = $username . '_' . $password;
        $hash = md5($str);
        return $this->md5ToInt($hash);
    }

    /*
     * for generating nonce
     */
    public function genRandomStr( $length = 6 ) {
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $ret = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            $ret .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $ret;
    }

    /**
     * description: 根据domain 、token、openid 生成 免导入登陆模型
     * @param domain   应用申请的domain
     * @param token    应用申请的token
     * @param openid   用户ID
     * @param terminal 平台 ios、web、android
     * @return array  数组
     */
    public function getLoginModel($openid,$terminal)
    {

        $appKey = $this->_appkey[$terminal];
        $secret =  $this->_appsecret[$terminal];

        $nonce = $this->genRandomStr(6);
        $timestamp = time();


        $signature_array=array(
            $this->_token,
            $secret,
            (string)$openid,
            $nonce,
            (string)$timestamp,
        );

        sort($signature_array, SORT_STRING);
        $signature= hash('sha256',(implode($signature_array)));

        $model = array();
        $model['appKey'] = $appKey;
        $model['nonce'] = $nonce;
        $model['timestamp'] = $timestamp;
        $model['signature'] = $signature;
        $model['domain'] = $this->_domain;
        $model['openId'] = $openid;
        return $model;
    }

	
}